/*
 * Copyright 2010 Assert Developments
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.ad.coffeebreak.validation;

import be.ad.coffeebreak.exceptions.ValidationException;

import java.util.regex.Pattern;

/**
 * Validation utilities.
 * 
 * @author Stefan Bangels
 */
public class ValidationUtils {

    private static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile("^\\w+([_\\.-]\\w+)*@(\\w+([_\\.-]\\w+)*)$");

    public static void assertNotNull(Object o, String message) {
        if (o == null) {
            throw new IllegalArgumentException(message);
        }
    }

    public static void rejectIfEmptyOrWhitespace(String value, String message) throws ValidationException {
        if (value == null || value.trim().isEmpty()) {
            throw new ValidationException(message);
        }
    }

    public static void rejectIfTooLong(String value, int maxLength, String message) throws ValidationException {
        if (value != null && value.length() > maxLength) {
            throw new ValidationException(message);
        }
    }

    public static void rejectIfNotInValues(Object value, Object[] values, String message) throws ValidationException {
        for (Object o : values) {
            if (o == null && value == null) {
                return;
            } else if (o != null && o.equals(value)) {
                return;
            }
        }
        throw new ValidationException(message);

    }

    public static void rejectIfNotEmail(String value, String message) throws ValidationException {
        if (value != null && !EMAIL_ADDRESS_PATTERN.matcher(value).matches()) {
            throw new ValidationException(message);
        }
    }

    public static void validate(Object o, Validator validator, String message) throws ValidationException {
        try {
            validator.validate(o);
        } catch (ValidationException e) {
            throw new ValidationException(message, e);
        }
    }

}
